/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.core.config;

import hu.glassy.core.service.EmailService;
import hu.glassy.core.service.impl.EmailServiceImpl;
import java.io.IOException;
import javax.mail.Session;
import javax.naming.NamingException;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jndi.JndiTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;

/**
 * Configuration of the email sending services
 *
 * @author molnar.alexander@sonrisa.hu
 */
@Configuration
public class EmailConfig
{

  @Bean
  public JavaMailSender mailSender() throws NamingException
  {
    final JndiTemplate jndiTemplate = new JndiTemplate();
    final Session session = jndiTemplate.lookup("java:/comp/env/mail/Session", Session.class);

    final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setSession(session);
    return mailSender;
  }

  @Bean
  public VelocityEngine velocityEngine() throws VelocityException, IOException
  {
    final VelocityEngineFactoryBean factoryBean = new VelocityEngineFactoryBean();
    factoryBean.setResourceLoaderPath("classpath:/template");
    factoryBean.setPreferFileSystemAccess(false);
    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
  }

  @Bean
  public EmailService emailService()
  {
    return new EmailServiceImpl();
  }
}
